package com.gqzdev.xblog.controller.home;


import com.gqzdev.xblog.entity.Comment;
import com.gqzdev.xblog.entity.News;
import com.gqzdev.xblog.entity.NewsCategory;
import com.gqzdev.xblog.entity.Newsuser;
import com.gqzdev.xblog.page.Page;
import com.gqzdev.xblog.service.CommentService;
import com.gqzdev.xblog.service.DescriptionService;
import com.gqzdev.xblog.service.NewsCategoryService;
import com.gqzdev.xblog.service.NewsService;
import com.gqzdev.xblog.util.WebUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
public class HomeNewsController {

    @Autowired
    private NewsCategoryService newsCategoryService;

    @Autowired
    private NewsService newsService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private DescriptionService descService;

    @Autowired
    private WebUtil webUtil;


    /**
     * 查看新闻详情
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public ModelAndView detail(ModelAndView model, Long id, HttpServletRequest request) {
        model.addObject("newsCategoryList", newsCategoryService.findAllShow());
        News news = newsService.find(id);
        // 空指针异常
        if (news.getPhoto().equals("/image/news-pic.jpg")){
            news.setPhoto(null);
        }
        model.addObject("news", news);
        model.addObject("title", news.getTitle());
        model.addObject("tags", news.getTags().split(","));
        model.setViewName("home/news/detail");
        //查看数加1
        newsService.updateViewNumber(id);

        // 获取网站信息  保存到session中
        request.getSession().setAttribute("header_topbar",descService.queryById(1));
        request.getSession().setAttribute("logo_content",descService.queryById(2));
        request.getSession().setAttribute("about",descService.queryById(5));
        request.getSession().setAttribute("tag",descService.queryById(6));
        return model;
    }

    /**
     * 按照分类显示新闻列表
     *
     * @param model
     * @param cid
     * @return
     */
    @RequestMapping(value = "/category_list", method = RequestMethod.GET)
    public ModelAndView categoryList(ModelAndView model,
                                     @RequestParam(name = "cid", required = true) Long cid, Page page) {
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("offset", 0);
        queryMap.put("pageSize", 10);
        queryMap.put("categoryId", cid);
        model.addObject("newsCategoryList", newsCategoryService.findAllShow());
        List<News> newsList = newsService.findListNoDel(queryMap);
        for (News news:newsList){
            webUtil.removeHtml(news);
            if (news.getPhoto().equals("/image/news-pic.jpg")){
                news.setPhoto(null);
            }
        }
        model.addObject("newsList", newsList);
        NewsCategory newsCategory = newsCategoryService.find(cid);
        model.addObject("newsCategory", newsCategory);
        model.addObject("title", newsCategory.getName() + "分类下的新闻信息");
        model.setViewName("home/news/category_list");
        return model;
    }

    /**
     *  sidebar 侧边栏位发布时间最新的
     *  最新发布的最新n条信息
     *  获取已经审核的
     * @return
     */
    @RequestMapping(value = "/last_news_list", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> lastNewsList() {
        Map<String, Object> ret = new HashMap<String, Object>();
        ret.put("type", "success");
        List<News> lastNewsList = newsService.findLastNewsList(10);
        for (News news: lastNewsList){
            if (news.getPhoto().equals("/image/news-pic.jpg")){
                news.setPhoto(null);
            }
        }
        ret.put("newsList",lastNewsList);
        return ret;
    }

    /**
     *  sidebar 侧边栏位评论 最新
     */
    @RequestMapping(value = "/last_comment_list", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> lastCommentList() {
        Map<String, Object> ret = new HashMap<String, Object>();
        ret.put("type", "success");
        List<News> lastCommentList = newsService.findLastCommentList(10);
        for (News news: lastCommentList){
            if (news.getPhoto().equals("/image/news-pic.jpg")){
                news.setPhoto(null);
            }
        }
        ret.put("newsList",lastCommentList );
        return ret;
    }


    /**
     *  sidebar 侧边栏位评论数目最多的
     * 获取按评论数排序的最新n条信息
     *  获取已经审核的
     * @return
     */
    @RequestMapping(value = "/most_comment_list", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> mostCommentList() {
        Map<String, Object> ret = new HashMap<String, Object>();
        ret.put("type", "success");
        List<News> mostCommentList = newsService.findMostCommentList(10);
        for (News news: mostCommentList){
            if (news.getPhoto().equals("/image/news-pic.jpg")){
                news.setPhoto(null);
            }
        }
        ret.put("newsList", mostCommentList);
        return ret;
    }


    /**
     * 分页获取某个分类下的文章
     *
     * @param page
     * @param cid
     * @return
     */
    @RequestMapping(value = "/get_category_list", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getCategoryList(Page page, @RequestParam(name = "cid", required = true) Long cid
    ) {
        Map<String, Object> ret = new HashMap<String, Object>();
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("offset", page.getOffset());
        queryMap.put("pageSize", page.getRows());
        queryMap.put("categoryId", cid);
        ret.put("type", "success");
        List<News> newsList = newsService.findListNoDel(queryMap);
        for (News news: newsList){
            webUtil.removeHtml(news);
            if (news.getPhoto().equals("/image/news-pic.jpg")){
                news.setPhoto(null);
            }
        }
        ret.put("newsList", newsList);
        return ret;
    }


    /**
     * 分页获取某个分类下的文章
     *
     * @param page
     * @return
     */
    @RequestMapping(value = "/get_index_list", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getIndexList(Page page){
        Map<String, Object> ret = new HashMap<String, Object>();
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("offset", page.getOffset());
        queryMap.put("pageSize", page.getRows());
        ret.put("type", "success");
        List<News> newsList = newsService.findListNoDel(queryMap);
        for (News news: newsList){
            webUtil.removeHtml(news);
            if (news.getPhoto().equals("/image/news-pic.jpg")){
                news.setPhoto(null);
            }
        }
        ret.put("newsList", newsList);
        return ret;
    }




    /**
     * 获取搜索列表
     *
     * @param model
     * @param keyword
     * @param page
     * @return
     */
    @RequestMapping(value = "/search_list", method = RequestMethod.GET)
    public ModelAndView searchList(ModelAndView model, @RequestParam(name = "keyword", required = false, defaultValue = "") String keyword, Page page ) {
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("offset", 0);
        queryMap.put("pageSize", 10);
        queryMap.put("title", keyword);
        model.addObject("newsCategoryList", newsCategoryService.findAllShow());
        List<News> newsList = newsService.findListNoDel(queryMap);
        for (News news: newsList){
            webUtil.removeHtml(news);
            if (news.getPhoto().equals("/image/news-pic.jpg")){
                news.setPhoto(null);
            }
        }
        model.addObject("newsList", newsList);
        model.addObject("title", keyword + "关键字下的新闻信息");
        model.addObject("keyword", keyword);
        model.setViewName("home/news/search_list");
        return model;
    }

    /**
     * 分页加载搜索列表
     *
     * @param page
     * @param keyword
     * @return
     */
    @RequestMapping(value = "/get_search_list", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getSearchList(Page page,
        @RequestParam(name = "keyword", required = false, defaultValue = "") String keyword) {
        Map<String, Object> ret = new HashMap<String, Object>();
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("offset", page.getOffset());
        queryMap.put("pageSize", page.getRows());
        queryMap.put("title", keyword);
        ret.put("type", "success");
        List<News> newsList = newsService.findListNoDel(queryMap);
        for (News news: newsList){
            webUtil.removeHtml(news);
            if (news.getPhoto().equals("/image/news-pic.jpg")){
                news.setPhoto(null);
            }
        }
        ret.put("newsList", newsList);
        return ret;
    }

    /**
     * 添加评论
     *
     * @param comment
     * @return
     */
    @RequestMapping(value = "/comment_news", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> commentNews(Comment comment, HttpSession session) {
        Map<String, Object> ret = new HashMap<String, Object>();
        Newsuser newsuser = (Newsuser)session.getAttribute("newsuser");
        if (null == newsuser){
            ret.put("type", "error");
            ret.put("msg", "您还未登录！请登录！");
            return ret;
        }
        if (comment == null) {
            ret.put("type", "error");
            ret.put("msg", "请填写完整的评论信息！");
            return ret;
        }
        if (comment.getNewsId() == null) {
            ret.put("type", "error");
            ret.put("msg", "请选择一个文章进行评论！");
            return ret;
        }
        /*
        if (StringUtils.isEmpty(comment.getNickname())) {
            ret.put("type", "error");
            ret.put("msg", "请填写昵称！");
            return ret;
        }
        */
        if (StringUtils.isEmpty(comment.getContent())) {
            ret.put("type", "error");
            ret.put("msg", "请填写评论内容！");
            return ret;
        }
        comment.setUid(newsuser.getUid());
        comment.setNickname(newsuser.getName());
        comment.setCreateTime(new Date());
        if (commentService.add(comment) <= 0) {
            ret.put("type", "error");
            ret.put("msg", "评论失败，请联系管理员！");
            return ret;
        }
        //文章评论数加1
        newsService.updateCommentNumber(comment.getNewsId());
        ret.put("type", "success");
        ret.put("createTime", comment.getCreateTime());
        return ret;
    }

    /**
     * 分页获取某一文章的评论
     *
     * @param page
     * @return
     */
    @RequestMapping(value = "/get_comment_list", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getCommentList(Page page, Long newsId) {
        Map<String, Object> ret = new HashMap<String, Object>();
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("offset", page.getOffset());
        queryMap.put("pageSize", page.getRows());
        queryMap.put("newsId", newsId);
        ret.put("type", "success");
        ret.put("commentList", commentService.findListShow(queryMap));
        return ret;
    }
}
